//检查登陆状态
isLogining = () => {
    let isloging = sessionStorage.getItem("isLogin");
    if (isloging) {
        isloging = (JSON.parse(isloging));
        $('#userName span').html(isloging.userName);
        return { 'role': isloging.userRole, 'id': isloging.userId };
    } else {
        $(window).attr('location', './login.html');
    }
}
//登陆
login = () => {
    let accout = $("#userName").val();
    let password = $("#password").val();
    $.ajax({
        url: '/xjrest/account/web/login',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            "account": accout,
            "password": password
        }),
        success: function (data) {

            var data = eval("(" + data + ")");
            if (data.ret.success && data.ret.value.secret == "c17f8f3d8e2f39389474296b8fd116ed") {
                loginUser = data.ret.value;
                loginUser["account"] = data.args.account;
                sessionStorage.setItem('isLogin', JSON.stringify(loginUser));
                sessionStorage.setItem('appid', 25);
                $(window).attr('location', './index.html');
            } else {
                $('.noEmpty').html('用户名或密码错误');
            }
        }
    })
}


//退出登陆
logOut = () => {
    sessionStorage.removeItem("isLogin");
    $(window).attr('location', './login.html');
}

//检测节点变化
watchDom = (dom, func) => {
    var title = $("b.facility");
    var title = $(dom); //the element I want to monitor 
    title.bind('DOMNodeInserted', function (e) {
        func();
    });
}
//限制只能输入数字
JHshNumberText = (a) => {
    var fa = "";
    if (a.value.substring(0, 1) == "-")
        fa = "-";
    var str = (a.value.replace(/[^0-9.]/g, '')).replace(/[.][0-9]*[.]/, '.');
    if (str.substring(0, 1) == ".")
        str = "0" + str;
    a.value = fa + str;
}

//获取元素的绝对位置

getElemSeat = (obj) => {
    var pos = { "top": 0, "left": 0 };
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            pos.top += obj.offsetTop;
            pos.left += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        pos.left += obj.x;
    } else if (obj.x) {
        pos.top += obj.y;
    }
    return { x: pos.left, y: pos.top };
}

//ajax

Ajax = (url, callBack, parms, type, asy) => {
    $.ajax({
        url: url,
        type: type ? type : 'get',
        data: parms ? parms : '',
        traditional: true,
        contentType: "application/json",
        async: asy ? asy : true,
        success: function (result) {
            let data;
            if (typeof result == 'string') {
                data = JSON.parse(result);
            } else {
                data = result;
            }
            callBack(data);
        }
    });
}

//格式化日期 DateFormat('yyyy_MM_dd hh:mm:ss:SS 星期w 第q季度')  
DateFormat = (format, date) => {
    if (!date) {
        date = new Date();
    }
    var Week = ['日', '一', '二', '三', '四', '五', '六'];
    var o = {
        "y+": date.getYear(), //year  
        "M+": date.getMonth() + 1, //month   
        "d+": date.getDate(), //day   
        "h+": date.getHours(), //hour   
        "H+": date.getHours(), //hour  
        "m+": date.getMinutes(), //minute   
        "s+": date.getSeconds(), //second   
        "q+": Math.floor((date.getMonth() + 3) / 3), //quarter   
        "S": date.getMilliseconds(), //millisecond   
        "w": Week[date.getDay()]
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

// 加载 CSS 文件  
loadStyle = (url) => {
    try {
        document.createStyleSheet(url)
    } catch (e) {
        var cssLink = document.createElement('link');
        cssLink.rel = 'stylesheet';
        cssLink.type = 'text/css';
        cssLink.href = url;
        var head = document.getElementsByTagName('head')[0];
        head.appendChild(cssLink)
    }
}

//截取指定长度字符串,超出末尾补'...'
truncate = (target, length, truncate) => {
    length = length || 20;
    truncate = truncate === void (0) ? '...' : truncate;

    return target.length > length ?
        target.slice(0, length - truncate.length) + truncate : String(target);
}

//将后台返回list数据转为map
setModule = (data) => {
    let modules = {};
    $.each(data, function (index, el) {
        modules[index] = el;
    });

    return modules;
}

//监测非空
checkInput = (dom) => {
    let puts = $(dom + ' input');
    let type = 0;
    $.each(puts, function (index, el) {
        if (!$(el).is(':hidden') && $(el).val() == '') {
            $(this).addClass('empty');
            type = 1;
        }
    });

    return type;
}

checkBlur = (dom) => {
    $(dom + ' input').blur(function () {
        if ($(this).val() == '') {
            $(this).addClass('empty');
        } else {
            $(this).removeClass('empty');
        }
    });
}

//ztree
setTree = (dom, set, callback) => {
    var setting = set;
    set.async.url = getAsyncUrl;
    set.async.dataFilter = filter;

    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        for (var i = 0, l = childNodes.length; i < l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
            if (childNodes[i].type != 2) {
                childNodes[i].isParent = true;
                childNodes[i].iconClose = "./js/lib/zTree/css/zTreeStyle/img/diy/1_close.png";
                childNodes[i].iconOpen = "./js/lib/zTree/css/zTreeStyle/img/diy/1_open.png";
            } else {
                childNodes[i].icon = "./js/lib/zTree/css/zTreeStyle/img/diy/3.png";
            }
        }
        let allNodes;
        if (typeof (parentNode) == 'undefined') {
            allNodes = [{
                'id': 320113,
                'parentId': '',
                'state': '',
                'children': childNodes,
                'open': true,
                'name': '栖霞区',
                'iconClose': "./js/lib/zTree/css/zTreeStyle/img/diy/1_close.png",
                'iconOpen': "./js/lib/zTree/css/zTreeStyle/img/diy/1_open.png"
            }]
        } else {
            allNodes = childNodes;
        }

        return allNodes;
    }

    $(document).ready(function () {
        $.fn.zTree.init($(dom), setting);
    });

    function getAsyncUrl(treeId, treeNode) {
        var orgid = 320113;
        var url = "/xjrest/area/area_tree";
        if (!treeNode) {
            url = url + "?parentId=" + orgid + "&nodeType=1";
        } else {
            url = url + "?parentId=" + treeNode.id + "&nodeType=2";
        }

        return url;
    }
}

function setChildren(dom, id, set, checkedNodes) {
    Ajax("/xjrest/area/area_tree?parentId=" + id, treeChildBack, '', 'post');
    function treeChildBack(childNodes) {
        for (var i = 0, l = childNodes.length; i < l; i++) {
            if (checkedNodes) {
                let str = '';
                $.each(checkedNodes, function (index, el) {
                    if (el.villageName == childNodes[i].name) {
                        childNodes[i].checked = true;
                    }
                    str += el.villageName + ',';
                });
                $('#childPut').attr('title', str);
                $('#childPut').val(truncate(str, 15));
            }
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
            childNodes[i].icon = "./js/lib/zTree/css/zTreeStyle/img/diy/2.png";
        }
        let allNodes = [{
            'id': 320113,
            'parentId': '',
            'state': '',
            'children': childNodes,
            'open': true,
            'name': '全选',
            'iconClose': "./js/lib/zTree/css/zTreeStyle/img/diy/1_close.png",
            'iconOpen': "./js/lib/zTree/css/zTreeStyle/img/diy/1_open.png"
        }]
        let setting = set;
        $.fn.zTree.init($(dom), setting, allNodes);
    }
}